from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from django.utils.html import format_html
from django.db import models
import datetime
import uuid

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
from django.utils.html import format_html
from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
import datetime
import random, os
# Create your models here.
from django.contrib.auth.models import AbstractUser
from django.db import models

ENV_PROFILE = os.getenv("ENV")
if ENV_PROFILE == "test":
    import itkf.test_settings as config
elif ENV_PROFILE == "production":
    import itkf.prd_settings as config
else:
    import itkf.settings as config

corpid = config.weChatWork["corpid"]
sourceFile = config.weChatWork["sourceFile"]
media_image_url = config.weChatWork["media_image_url"]


def rename(newname):
    def decorator(fn):
        fn.__name__ = newname
        return fn

    return decorator


def newImageName(instance, filename):
    filename = '{}.{}'.format(uuid.uuid4().hex, "png")
    return filename


# 生成预约订单号

# 用时间生成一个唯一随机数

def random_with_N_digits(n):
    range_start = 10 ** (n - 1)
    range_end = (10 ** n) - 1
    return random.randint(range_start, range_end)


def get_ran_dom():
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
    randomNum = random_with_N_digits(3)  # 生成的随机整数n，其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum)
    uniqueNum = str(nowTime) + str(randomNum)
    return uniqueNum



# 应用管理
class agent(models.Model):
    name = models.CharField(max_length=225, verbose_name="部门名称", blank=True, default="")
    agentid = models.CharField(max_length=225, verbose_name="应用ID", blank=True, default="")
    secret = models.CharField(max_length=225, verbose_name="应用密钥", blank=True, default="")
    avatar = models.ImageField(max_length=225, verbose_name="部门Logo", blank=True, default="")
    conversationTime = models.IntegerField(verbose_name="会话时长(分钟)", default=20)
    webhook_url = models.URLField(verbose_name="群机器人地址", default="", blank=True, null=True)

    createTime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lastTime = models.DateTimeField(auto_now=True, verbose_name="修改时间")
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="创建者",
                               related_name="agent_author")
    editor = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="修改者",
                               related_name="agent_creator")

    @rename("部门Logo")
    def showAvatar(self):
        return format_html("<img src='{}{}' style='width: 60px;height: 60px;' class='showAvatar' />", media_image_url,
                           self.avatar)

    @rename("详情")
    def checkMessage(self):
        return format_html("<a href='/app/index/{}.html' target='blank'>回复</a>", self.id)

    class Meta:
        verbose_name = verbose_name_plural = '部门管理'
        ordering = ['id']

    def __str__(self):
        return self.name

# 客服人员
class KF(models.Model):
    agent = models.ForeignKey(agent, null=True, on_delete=models.CASCADE, verbose_name="应用名称")
    username = models.CharField(max_length=225, verbose_name="姓名", blank=True, default="")
    userid = models.CharField(max_length=225, verbose_name="UM", blank=True, default="")
    status = models.BooleanField(verbose_name="是否在线", default=False)
    avatar = models.ImageField(max_length=225, verbose_name="头像", blank=True, default="")
    createTime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lastTime = models.DateTimeField(auto_now=True, verbose_name="修改时间")
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="创建者",
                               related_name="kf_author")
    editor = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="修改者",
                               related_name="kf_creator")

    class Meta:
        verbose_name = verbose_name_plural = '在线客服'
        ordering = ['id']

    @rename("头像")
    def showAvatar(self):
        return format_html("<img src='{}{}' style='width: 60px;height: 60px;' class='showAvatar' />", media_image_url,
                           self.avatar)

    def __str__(self):
        return self.username


# 行内员工

def randomSign():
    switch = {
        0: "只要还有明天，今天就永远是起跑线。",
        1: "只要还有明天，今天就永远是起跑线。",
        2: "只要还有明天，今天就永远是起跑线。"
    }
    return switch[0]


class userList(models.Model):
    agent = models.ForeignKey(agent, null=True, on_delete=models.CASCADE, verbose_name="应用名称")
    username = models.CharField(max_length=225, verbose_name="姓名", blank=True, default="")
    userid = models.CharField(max_length=225, verbose_name="UM", blank=True, default="")
    avatar = models.ImageField(max_length=225, verbose_name="头像", blank=True, default="")
    sign = models.CharField(max_length=225, verbose_name="个性签名", blank=True, default=randomSign)

    ISLEAD_CHOICES = ((0, '是'), (1, '否'),)
    islead = models.IntegerField(choices=ISLEAD_CHOICES, verbose_name="等级", default=1)
    createTime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lastTime = models.DateTimeField(auto_now=True, verbose_name="修改时间")
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="创建者",
                               related_name="userlist_author")
    editor = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="修改者",
                               related_name="userlist_creator")

    @rename("头像")
    def showAvatar(self):
        return format_html("<img src='{}{}' style='width: 60px;height: 60px;' class='showAvatar' />", media_image_url,
                           self.avatar)

    class Meta:
        verbose_name = verbose_name_plural = '用户列表'
        ordering = ['id']

    def __str__(self):
        return self.username


# 接受的消息

class Message(models.Model):
    ToUserName = models.CharField(max_length=225, verbose_name="接受者", blank=True, default="")
    FromUserName = models.CharField(max_length=225, verbose_name="发送者", blank=True, default="")
    CreateTime = models.DateTimeField(verbose_name="发送时间", blank=True, default=None)
    MsgId = models.CharField(max_length=225, verbose_name="消息ID", blank=True, default="")
    AgentID = models.CharField(max_length=225, verbose_name="部门名称", blank=True, default="")
    MsgType = models.CharField(max_length=225, verbose_name="消息类型", blank=True, default="")
    content = models.TextField(max_length=2000, verbose_name="消息内容", blank=True, default="")
    userList = models.ForeignKey('userList', null=True, to_field="id", on_delete=models.CASCADE)
    createDateTime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lastTime = models.DateTimeField(auto_now=True, verbose_name="修改时间")
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="创建者",
                               related_name="message_author")
    editor = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="修改者",
                               related_name="message_creator")

    class Meta:
        verbose_name = verbose_name_plural = '所有消息'
        ordering = ['id']

    def __str__(self):
        return self.FromUserName





# 员工服务
class staffService(models.Model):
    agent = models.ForeignKey('agent', null=True, on_delete=models.CASCADE, verbose_name="应用名称")
    title = models.CharField(max_length=225, verbose_name="标题", blank=True, default="")
    avatar = models.ImageField(max_length=225, verbose_name="头像", blank=True, default="")
    desc = models.TextField(max_length=500, verbose_name="描述", default="", blank=True, null=True)

    welcomeText = models.TextField(max_length=2000, verbose_name="欢迎语", blank=True, default="")
    firstText = models.TextField(max_length=2000, verbose_name="会话提示语", blank=True, default="您好，很高兴为您服务!")

    notuserText = models.TextField(max_length=2000, verbose_name="客服不在线提示语", blank=True,
                                   default="非常抱歉，客服处于离线状态，您的消息我们已发送IT服务台，马上会有IT同事跟进处理!")

    createTime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lastTime = models.DateTimeField(auto_now=True, verbose_name="修改时间")
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="创建者",
                               related_name="staffService_author")
    editor = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="修改者",
                               related_name="staffService_creator")

    class Meta:
        verbose_name = verbose_name_plural = '员工服务'
        ordering = ['createTime']

    @rename("头像")
    def showAvatar(self):
        return format_html("<img src='{}{}' style='width: 60px;height: 60px;' class='showAvatar' />", media_image_url,
                           self.avatar)

    def __str__(self):
        return self.title


class knowledgeBase(models.Model):
    questionType = models.CharField(max_length=225, verbose_name="问题类型", blank=True, default="")
    key = models.CharField(max_length=225, verbose_name="关键字", blank=True, default="")
    rule = models.IntegerField(choices=((0, '包含'), (1, '完全匹配')), default=0, verbose_name='规则')
    answerType = models.IntegerField(choices=((0, '文字'), (1, '图文'), (2, '图片'), (3, '语音'), (4, '视频')), default=0,
                                     verbose_name='发送类型')
    content = models.TextField(max_length=2000, verbose_name="消息内容", blank=True, default="")
    createTime = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    lastTime = models.DateTimeField(auto_now=True, verbose_name="修改时间")
    author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="创建者",
                               related_name="knowledgeBase_author")
    editor = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="修改者",
                               related_name="knowledgeBase_creator")

    class Meta:
        verbose_name = verbose_name_plural = '知识库'
        ordering = ['id']

    def __str__(self):
        return self.content